using System.IO;
using System.Net;
using log4net.Core;
using Quiki.Services;

namespace Quiki.DocumentGraphProcessors
{
    public class DocumentFilesUploader : IDocumentGraphProcessor
    {
        public DocumentFilesUploader(
            DocumentProcessorSettings settings,
            FileSet documentFiles,
            IFtpClient ftpClient,
            ILogger logger)
        {
            this.settings = settings;
            this.documentFiles = documentFiles;
            this.ftpClient = ftpClient;
            this.logger = logger;
        }

        public void Execute(DocumentGraph documentGraph)
        {
            //  new FtpConnection(settings.FtpServer, settings.FtpUserName, settings.FtpPassword
            ftpClient.Credentials = new NetworkCredential(settings.FtpUserName, settings.FtpPassword);
            ftpClient.Host = settings.FtpServer;
            using (IFtpConnection ftp = ftpClient.Open())
            {
                logger.Log(Level.Info, "Logging into the FTP server");

                logger.Log (Level.Info, "Changing the remote directory");

                ftp.ChangeDirectory(settings.FtpRemoteDir);

                foreach (string fileName in documentFiles)
                {
                    string localFile = Path.Combine(settings.OutputDir, fileName);
                    string remoteFile = fileName.Replace('\\', '/');

                    string remoteDir = Path.GetDirectoryName(remoteFile);

                    if (false == string.IsNullOrEmpty(remoteDir)
                        && false == ftp.DirectoryExists (remoteDir))
                    {
                        logger.Log (Level.Info, "Creating remote directory '{0}'", remoteDir);
                        ftp.CreateDirectory(remoteDir);
                    }

                    logger.Log (Level.Info, "Uploading file '{0}'", fileName);
                    ftp.PutFile (localFile, remoteFile);
                }
            }
        }

        private readonly DocumentProcessorSettings settings;
        private readonly FileSet documentFiles;
        private readonly IFtpClient ftpClient;
        private readonly ILogger logger;
    }
}